package org.example.volunteerend.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.example.volunteerend.dto.PointsRecordRequest;
import org.example.volunteerend.entity.PointsRecord;
import org.example.volunteerend.mapper.PointsRecordMapper;
import org.example.volunteerend.mapper.UserMapper;
import org.example.volunteerend.service.PointsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PointsServiceImpl implements PointsService {

    private final PointsRecordMapper pointsRecordMapper;
    private final UserMapper userMapper;
    
    @Autowired
    public PointsServiceImpl(PointsRecordMapper pointsRecordMapper, UserMapper userMapper) {
        this.pointsRecordMapper = pointsRecordMapper;
        this.userMapper = userMapper;
    }
    
    @Override
    @Transactional
    public Map<String, Object> addPointsRecord(PointsRecordRequest request, Integer userId) {
        // 创建积分记录对象
        PointsRecord record = new PointsRecord();
        record.setUserId(userId);
        record.setPoints(request.getPoints());
        record.setReason(request.getReason());
        
        // 保存积分记录
        pointsRecordMapper.insert(record);
        
        // 更新用户积分
        userMapper.updatePoints(userId, request.getPoints());
        
        // 获取用户当前积分
        Integer currentPoints = userMapper.getUserPoints(userId);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("record_id", record.getRecordId());
        result.put("current_points", currentPoints);
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getPointsRanking(Integer limit) {
        // 默认值处理
        if (limit == null || limit <= 0) {
            limit = 50;
        }
        
        // 获取积分排行榜
        return pointsRecordMapper.findPointsRanking(limit);
    }
} 